package cn.school.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.school.entity.Admin;
import cn.school.service.AdminService;

@WebFilter(value = "/*", filterName = "rolef0")
public class AutoLoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("自动登录进入了");
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		if (req.getSession().getAttribute("USER_LOGIN") != null) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		String name = null, pass = null;
		Cookie[] cr = req.getCookies();
		for (int i = 0; cr != null && i < cr.length; i++) {
			Cookie cookie = cr[i];
			if (cookie.getName().equals("username"))
				name = cookie.getValue();

			if (cookie.getName().equals("userpass"))
				pass = cookie.getValue();

		}
		if (name == null || pass == null) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		AdminService admin = new AdminService();
		Admin user = admin.login(name, pass);
		if (user != null) {
			req.getSession().setAttribute("USER_LOGIN", user);
			// 请求的登录，可以跳转
			if (req.getServletPath().equals("/login.jsp") || req.getServletPath().equals("/LoginServlet")) {
				resp.sendRedirect(req.getContextPath() + "/success.jsp");
				return;
			}
			arg2.doFilter(arg0, arg1);
			return;
		}
		// 删掉cookie
		Cookie u1 = new Cookie("username", "1");
		Cookie p1 = new Cookie("userpass", "1");
		u1.setMaxAge(0);
		p1.setMaxAge(0);
		resp.addCookie(u1);
		resp.addCookie(p1);
		arg2.doFilter(arg0, arg1);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO 自动生成的方法存根

	}

}
